package com.atguigu.spzx.manager.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.atguigu.spzx.manager.mapper.CategoryMapper;
import com.atguigu.spzx.model.dto.excel.CategoryExcelDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * title:
 * author: zgl
 * date: 2024/1/3
 * description：
 */
@Component
public class ExcelListener extends AnalysisEventListener<CategoryExcelDto> {
    @Autowired
    private CategoryMapper categoryMapper;

    private List<CategoryExcelDto> list = new ArrayList<>();
    private Integer limit = 100;

    @Override
    public void invoke(CategoryExcelDto data, AnalysisContext analysisContext) {
        if (categoryMapper.exist(data)) {
            return;
        }
        list.add(data);
        if (list.size() >= limit) {
            categoryMapper.batchInsert(list);
            list.clear();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        //添加为达到limit的数据
        if (list.size() >= 0) {
            categoryMapper.batchInsert(list);
            list.clear();
        }
    }
}
